#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <vector>

#include "serializable.hpp"
#include "consumer.hpp"

std::vector<Consumer*> consumers;

void consume(std::string s) {
  for (int i = 0; i < consumers.size(); ++i) {
    if (consumers[i]->consume(s)) {
      break;
    }
  }
}

int main() {
  consumers.push_back(new ConsumerA());
  consumers.push_back(new ConsumerB());
  consumers.push_back(new ConsumerC());

  int sock, listener;
  struct sockaddr_in addr;
  char buf[1024];
  int bytes_read;
  listener = socket(AF_INET, SOCK_STREAM, 0);
  if (listener < 0) {
    perror("socket");
    return errno;
  }
  addr.sin_family = AF_INET;
  addr.sin_port = htons(8888);
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  if (bind(listener, (struct sockaddr *)&addr, 
           sizeof(addr)) < 0) {
    perror("bind");
    return errno;
  }
  listen(listener, 1);
  while (1) {
    sock = accept(listener, NULL, NULL);
    if (sock < 0) {
      perror("accept");
      return errno;
    }
    while (1) {
      bytes_read = recv(sock, buf, 1024, 0);
      if (bytes_read <= 0) break;
      std::cout << "Received from client " << buf << std::endl;
      consume(std::string(buf));
      send(sock, buf, bytes_read, 0);
    }
    close(sock);
  }
  return 0;
}
